package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JFileChooser;
import model.Piece;
import model.Sequence;
import view.GUI;

/**
 * Listens for events where the request is to save the current Piece
 */
public class SavePieceListener implements ActionListener {

	//ActionCommands this listener can handle
	public static final String SAVE = "SAVE", CONVERT = "CONVERT";

	private Piece piece;
	private GUI gui;

	public SavePieceListener(Piece piece, GUI gui) {
		this.piece = piece;
		this.gui = gui;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		gui.getMenuPanel().getPauseButton().doClick(); //Manually pause the Player

		String command = e.getActionCommand();

		//Show dialog for save file location
		JFileChooser chooser = new JFileChooser();
		chooser.setDialogTitle(
			command.charAt(0) + command.substring(1).toLowerCase() + " Piece"
		);
		int ret = chooser.showSaveDialog(gui);
		if(ret != JFileChooser.APPROVE_OPTION) return;

		File selectedFile = chooser.getSelectedFile();

		if(command.equals(SAVE)) {
			this.savePiece(selectedFile); //Save the Piece
		} else if(command.equals(CONVERT)) {
			/**
			 * Code removed, AudioContext.record() crashes program.
			 */
		}
	}

	/**
	 * Saves the Piece's data to the given file. The format of the file is:<br>
	 * {NAME}+{TEMPO}+{LENGTH};{INSTRUMENT_0}:{VOLUME_0}:{NOTE_0_0}.{NOTE_0_1}...{NOTE_0_N}.+...+{INSTRUMENT_N}...{NOTE_N_N}.
	 * @param file The file to write in.
	 */
	private void savePiece(File file) {
		String path = file.getAbsolutePath();

		//Check if file extension is MSQ, if not, append it.
		int dotIndex = path.lastIndexOf(".");
		if(dotIndex < 0) {
			file = new File(path+".msq");
		} else {
			String ext = path.substring(dotIndex+1);
			if(!ext.equals("msq")) {
				file = new File(path+".msq");
			}
		}

		//Create the String to be written onto the file contains the Piece's data.
		String saveString = piece.getName() + "+" + piece.getTempo() + "+" + piece.getLength() + ";";

		for(Sequence sequence : piece.getSequences()) {
			saveString += sequence.getInstrument() + ":" + sequence.getVolume() + ":";
			for(int note : sequence.getAllNotes()) {
				saveString += note + ".";
			}
			saveString += "+";
		}

		//Write it.
		try {
			Writer output = new BufferedWriter(new FileWriter(file));
			output.write(saveString);
			output.close();
		} catch(IOException ioe) {
			System.out.println("Failed to save to file " + file.getAbsolutePath());
		}
	}

}
